<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 内容区域 -->
    <section class="space-y-4 pb-16">
      <!-- 筛选条件区域 -->
      <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
        <!-- 范围时间选择 -->
        <div class="grid grid-cols-2 gap-2 mb-3">
          <input type="date" v-model="startDate"
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="开始日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
          <input type="date" v-model="endDate"
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="结束日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
        </div>

        <!-- 快捷时间选项 -->
        <div class="flex gap-1">
          <button v-for="option in quickOptions" :key="option.value"
                  @click="selectQuickOption(option.value)"
                  :class="[
                    'px-3 py-1.5 rounded text-sm font-medium transition-all whitespace-nowrap flex-1',
                    quickTime === option.value
                      ? 'bg-brand-500 text-white border border-brand-500'
                      : 'bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-200'
                  ]">
            {{ option.label }}
          </button>
        </div>
      </div>

      <!-- 排名列表 -->
      <div class="space-y-3">
        <div v-if="loading" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
          <div class="flex flex-col items-center justify-center space-y-3">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-500"></div>
            <div class="text-gray-500 text-sm">数据加载中...</div>
          </div>
        </div>

        <div v-else-if="rankedSites.length === 0" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
          <div class="flex flex-col items-center justify-center space-y-3">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-gray-300">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7C21 5.9 20.1 5 19 5H5C3.9 5 3 5.9 3 7V9C3 10.1 3.9 11 5 11H19C20.1 11 21 10.1 21 9ZM5 13H7V21H5V13ZM9 13H11V21H9V13ZM13 13H15V21H13V13ZM17 13H19V21H17V13Z"/>
            </svg>
            <div class="text-gray-500 text-sm">暂无符合条件的场站</div>
            <div class="text-gray-400 text-xs">请尝试调整筛选条件</div>
          </div>
        </div>

        <div v-else v-for="(site, index) in rankedSites" :key="site.stationId" class="bg-gray-50 rounded-lg p-4 shadow-sm border border-gray-200">
          <!-- 站点名称和排名 -->
          <div class="flex items-center gap-3 mb-3">
            <div v-if="index < 3" :class="[
              'w-8 h-8 rounded-full flex items-center justify-center text-white font-bold text-sm',
              index === 0 ? 'bg-yellow-500' : index === 1 ? 'bg-gray-400' : 'bg-orange-500'
            ]">
              {{ index + 1 }}
            </div>
            <div v-else class="w-8 h-8 rounded-full flex items-center justify-center bg-gray-100 text-gray-600 font-bold text-sm">
              {{ index + 1 }}
            </div>
            <div class="text-base font-semibold text-gray-900 truncate">{{ site.stationName }}</div>
          </div>

          <!-- 四个小卡片 -->
          <div class="grid grid-cols-4 gap-3">
            <div class="p-3 bg-gray-100 rounded-lg min-w-0 flex flex-col items-center justify-center">
              <div class="text-xs text-gray-500 mb-1 whitespace-nowrap">总服务费</div>
              <div class="text-sm font-medium text-gray-900 whitespace-nowrap">¥{{ formatNumber(site.totalServiceFee || 0) }}</div>
            </div>
            <div class="p-3 bg-gray-100 rounded-lg min-w-0 flex flex-col items-center justify-center">
              <div class="text-xs text-gray-500 mb-1 whitespace-nowrap">分成比例</div>
              <div class="text-sm font-medium text-gray-900 whitespace-nowrap">{{ site.shareRatio || '0%' }}</div>
            </div>
            <div class="p-3 bg-gray-100 rounded-lg min-w-0 flex flex-col items-center justify-center">
              <div class="text-xs text-gray-500 mb-1 whitespace-nowrap">实际收入</div>
              <div class="text-sm font-medium text-gray-900 whitespace-nowrap">¥{{ formatNumber(site.actualIncome || 0) }}</div>
            </div>
            <div class="p-3 bg-gray-100 rounded-lg min-w-0 flex flex-col items-center justify-center">
              <div class="text-xs text-gray-500 mb-1 whitespace-nowrap">其他</div>
              <div class="text-sm font-medium text-gray-900 whitespace-nowrap">¥{{ formatNumber(site.otherFee || 0) }}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { post } from '../utils/request'

const router = useRouter()



// 接口请求相关
const loading = ref(false)
const rankedSites = ref([])

// 时间筛选相关
const quickTime = ref('today') // 默认今天
const startDate = ref('')
const endDate = ref('')

// 日期范围限制
const minDate = ref('2023-01-01') // 最早日期
const maxDate = computed(() => {
  const today = new Date()
  return formatDate(today)
})

// 快捷时间选项
const quickOptions = [
  { value: 'today', label: '今天' },
  { value: 'month', label: '本月' },
  { value: 'year', label: '今年' },
  { value: 'all', label: '全部' },
]

// 初始化日期
onMounted(() => {
  setQuickDate('today')
})

// 设置快捷时间
const setQuickDate = (type) => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

  switch (type) {
    case 'today':
      startDate.value = formatDate(today)
      endDate.value = formatDate(today)
      break
    case 'month':
      // 本月：1号至月末
      const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
      const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
      startDate.value = formatDate(startOfMonth)
      endDate.value = formatDate(endOfMonth)
      break
    case 'year':
      // 今年：1月1日至12月31日
      const startOfYear = new Date(today.getFullYear(), 0, 1)
      const endOfYear = new Date(today.getFullYear(), 11, 31)
      startDate.value = formatDate(startOfYear)
      endDate.value = formatDate(endOfYear)
      break
    case 'all':
      // 全部：2025年1月1日至今
      startDate.value = '2025-01-01' // 2025年1月1日
      endDate.value = formatDate(today)
      break
  }
}

// 选择快捷选项
const selectQuickOption = (value) => {
  quickTime.value = value
  setQuickDate(value)
}

// 处理日期选择
const handleDateChange = () => {
  if (startDate.value && endDate.value) {
    quickTime.value = 'custom'
    fetchRankData()
  }
}

// 获取排名数据
const fetchRankData = async () => {
  if (!startDate.value || !endDate.value) return
  
  loading.value = true
  try {
    // 使用统一的请求工具调用后端接口
    const result = await post('/h5/station/getRankStationList', {
      startDate: startDate.value,
      endDate: endDate.value
    })
    
    if (result.success) {
      rankedSites.value = result.data.list || []
    } else {
      console.error('获取排名数据失败:', result.message)
      rankedSites.value = []
    }
  } catch (error) {
    console.error('请求失败:', error)
    rankedSites.value = []
  } finally {
    loading.value = false
  }
}

// 监听日期变化，自动请求数据
watch([startDate, endDate], () => {
  if (startDate.value && endDate.value) {
    fetchRankData()
  }
})

// 日期格式化辅助函数
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 数值格式化函数
const formatNumber = (num) => {
  // 处理字符串和数字类型
  const number = typeof num === 'string' ? parseFloat(num) : num
  if (number >= 1000) {
    return (number / 1000).toFixed(1) + 'k'
  }
  return number.toFixed(2)
}
</script>
